// 导入样式
import './assets/main.css'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 初始化App和pinia
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)
const pinia = createPinia()
app.use(pinia)

// 使用 Element Plus
app.use(ElementPlus)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 导入appox
import { appox } from '@/appox/appox'
import { appoxCallback } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'
import { AppoxGeneralSample } from '@/appox/appox'
import { biBridge } from '@/appox/bi-bridge'

// 导入所有 store
import { useMessageDialogStore } from '@/stores/messageDialog'
import { useConfirmDialogStore } from '@/stores/confirmDialog'
import { useLogStore } from '@/stores/log'
import { useLanguageStore } from '@/stores/language'
import { useBusProtocolChooserStore } from '@/stores/busProtocolChooser'
import { useBusMessageChooserStore } from '@/stores/busMessageChooser'
import { useBusMessageAdderStore } from '@/stores/busMessageAdder'
import { useSignalChooserStore } from '@/stores/signalChooser'
import { useSignedSignalChooserStore } from '@/stores/signedSignalChooser'
import { useSignalAdderStore } from '@/stores/signalAdder'
import { useTaskBannerStore } from '@/stores/taskBanner'
import { useTaskDetailsStore } from '@/stores/taskDetails'
import { useSessionEditorStore } from '@/stores/sessionEditor'
import { useConnectionStore } from '@/stores/connection'
import { useControllerStore } from '@/stores/controller'
import { useToolPanelStore } from '@/stores/toolPanel'
import { useStandaloneTaskStore } from '@/stores/standaloneTask'
import { useConsoleProcedureStore } from '@/stores/consoleProcedure'
import { useContentTransferPanelStore } from '@/stores/contentTransferPanel'
import { useHtmlModuleStore } from '@/stores/htmlModule'
import { useInputStringStore } from '@/stores/inputString'
import { useSingleSelectStore } from '@/stores/singleSelect'
import { useMultiSelectStore } from '@/stores/multiSelect'
import { ConnectionBarType } from '@/stores/connection'
import { usePageDialogStore } from '@/stores/pageDialog'
import { useBusChannelsStore } from '@/stores/busChannels'
import { useVideoChannelsStore } from '@/stores/videoChannels'
import { useOtherChannelsStore } from '@/stores/otherChannels'
import { useSystemStatusStore } from '@/stores/systemStatus'
import { useVideoMonitorStore } from '@/stores/videoMonitor'
import { useSignalMonitorStore } from '@/stores/signalMonitor'
import { useBirdViewStore } from '@/stores/birdView'
import { useBusTracerStore } from '@/stores/busTracer'
import { usePointCloudMonitorStore } from '@/stores/pointCloudMonitor'

// 导入工具函数和常量
import { initializeColorTheme, printVersionText } from '@/utils/utility'
import { ProtoFilePath } from '@/utils/constants'
import audioPlayer from '@/utils/audioPlayer'

// 获取所有 store 实例
const messageDialogStore = useMessageDialogStore()
const confirmDialogStore = useConfirmDialogStore()
const logStore = useLogStore()
const languageStore = useLanguageStore()
const busProtocolChooserStore = useBusProtocolChooserStore()
const busMessageChooserStore = useBusMessageChooserStore()
const busMessageAdderStore = useBusMessageAdderStore()
const signalChooserStore = useSignalChooserStore()
const signedSignalChooserStore = useSignedSignalChooserStore()
const signalAdderStore = useSignalAdderStore()
const taskBannerStore = useTaskBannerStore()
const taskDetailsStore = useTaskDetailsStore()
const sessionEditorStore = useSessionEditorStore()
const connectionStore = useConnectionStore()
const controllerStore = useControllerStore()
const toolPanelStore = useToolPanelStore()
const standaloneTaskStore = useStandaloneTaskStore()
const consoleProcedureStore = useConsoleProcedureStore()
const contentTransferPanelStore = useContentTransferPanelStore()
const htmlModuleStore = useHtmlModuleStore()
const inputStringStore = useInputStringStore()
const singleSelectStore = useSingleSelectStore()
const multiSelectStore = useMultiSelectStore()
const pageDialogStore = usePageDialogStore()
const busChannelsStore = useBusChannelsStore()
const videoChannelsStore = useVideoChannelsStore()
const otherChannelsStore = useOtherChannelsStore()
const systemStatusStore = useSystemStatusStore()
const videoMonitorStore = useVideoMonitorStore()
const signalMonitorStore = useSignalMonitorStore()
const birdViewStore = useBirdViewStore()
const busTracerStore = useBusTracerStore()
const pointCloudMonitorStore = usePointCloudMonitorStore()

// 初始化回调
const initializeCallbacks = () => {
  appoxCallback.onAlert = (message, title) => {
    messageDialogStore.show(message, title)
  }

  appoxCallback.onConfirm = (message, title) => {
    return confirmDialogStore.show(message, title)
  }

  appoxCallback.onConfirmWithDefault = (message, title, defaultResult) => {
    return confirmDialogStore.show(message, title)
  }

  appoxCallback.onLog = (message, level) => {
    switch (level) {
      case appoxEnums.LogLevel.Info:
        logStore.addLog((languageStore.isChinese ? "[信息] " : "[INFO] ") + message, "Log")
        break
      case appoxEnums.LogLevel.Warning:
        logStore.addLog((languageStore.isChinese ? "[警告] " : "[WARN] ") + message, "Log")
        break
      case appoxEnums.LogLevel.Error:
        logStore.addLog((languageStore.isChinese ? "[错误] " : "[ERRR] ") + message, "Log")
        break
    }
  }

  appoxCallback.onDebugMessage = (message, source) => {
    logStore.addLog(message, source)
  }

  appoxCallback.onGetAppLanguage = () => {
    return languageStore.isChinese ? appoxEnums.Language.Chinese : appoxEnums.Language.English
  }

  appoxCallback.onSelectBusProtocolFiles = (selected) => {
    return busProtocolChooserStore.show(selected)
  }

  appoxCallback.onSelectBusMessage = (originID) => {
    return busMessageChooserStore.show(originID)
  }

  appoxCallback.onSelectBusMessages = (selected, availableCount) => {
    return busMessageAdderStore.show(selected, availableCount)
  }

  appoxCallback.onSelectSignal = async (originValueID, withSignBit, originSignBitID, withScale, originScale, unit) => {
    if (withSignBit) {
      return await signedSignalChooserStore.show(originValueID, originSignBitID, withScale ? originScale : null, unit)
    } else {
      let result = await signalChooserStore.show(originValueID, withScale ? originScale : null, unit)
      return [result[0], null, result[1]]
    }
  }

  appoxCallback.onSelectSignals = (selected, availableCount) => {
    return signalAdderStore.show(selected, availableCount)
  }

  appoxCallback.onRunStandaloneTask = (title, taskClassID, callback) => {
    return taskBannerStore.show(title, callback).then((checkDetails) => {
      if (checkDetails) {
        return taskDetailsStore.show(taskClassID, callback.getTaskConfig(), callback.getTaskReturnValue())
      }
    })
  }

  appoxCallback.onResetData = () => {
    biBridge.onResetData()
    busChannelsStore.onResetData()
    videoChannelsStore.onResetData()
    otherChannelsStore.onResetData()
    signalMonitorStore.onResetData()
    birdViewStore.onResetData()
    busTracerStore.onResetData()
    pointCloudMonitorStore.onResetData()
  }

  appoxCallback.onInputData = (data) => {
    if (data instanceof AppoxGeneralSample) {
      biBridge.onInputGeneralSample(data)
    }
    busChannelsStore.onInputData(data)
    videoChannelsStore.onInputData(data)
    otherChannelsStore.onInputData(data)
    signalMonitorStore.onInputData(data)
    birdViewStore.onInputData(data)
    busTracerStore.onInputData(data)
    pointCloudMonitorStore.onInputData(data)
    audioPlayer.onInputData(data)
  }

  appoxCallback.onStartSession = () => {
    logStore.addLog(languageStore.isChinese ? "Session开始。" : "Session started", "AppoxJsTest")
    appoxCallback.onResetData()
    audioPlayer.onStartSession()
    htmlModuleStore.unloadDevelPanel()
  }

  appoxCallback.onStopSession = () => {
    logStore.addLog(languageStore.isChinese ? "Session结束。" : "Session stopped", "AppoxJsTest")
    audioPlayer.onStopSession()
    htmlModuleStore.loadDevelPanel()
  }

  appoxCallback.onEditRecordedSession = (recordSessionID) => {
    sessionEditorStore.show(recordSessionID)
  }

  appoxCallback.onCheckPreferPRCWeb = () => {
    return true
  }

  appoxCallback.onConnectionChanged = (connected) => {
    if (connected) {
      connectionStore.updateConnectionBar(ConnectionBarType.Connection, "success", languageStore.isChinese ? "已链接" : "Connected")
      controllerStore.updateControllerPanelAvailability()
      toolPanelStore.updateToolPanelAvailability()
      standaloneTaskStore.updateTaskList()
      consoleProcedureStore.updateProcedureList()
      signalMonitorStore.onReconnected()
      busTracerStore.onConnected()
      pointCloudMonitorStore.onConnected()
    } else {
      connectionStore.resetConnectionBars()
    }
    htmlModuleStore.loadDevelPanel()
  }

  appoxCallback.onTransferStatistics = (stat) => {
    const connectionStore = useConnectionStore()
    connectionStore.updateTransferStatistics(stat)
  }

  appoxCallback.onRequestInputNumber = (message, defaultValue) => {
    return inputStringStore.show(message, defaultValue, true)
  }

  appoxCallback.onRequestInputString = (message, defaultValue) => {
    return inputStringStore.show(message, defaultValue, false)
  }

  appoxCallback.onRequestSingleSelect = (message, options, defaultSelectIndex) => {
    return singleSelectStore.show(message, options, defaultSelectIndex)
  }

  appoxCallback.onRequestMultiSelect = (message, options, defaultSelectIndices) => {
    return multiSelectStore.show(message, options, defaultSelectIndices)
  }
}

// 初始化应用
const initializeApp = async () => {

  // 初始化颜色主题
  initializeColorTheme()

  // 初始化回调
  initializeCallbacks()

  // 打印版本信息
  printVersionText()

  // 加载配置
  connectionStore.loadConnectionConfig()
  htmlModuleStore.loadHtmlModuleConfig()

  // 重置连接栏
  connectionStore.resetConnectionBars()

  // 初始化 Agency
  await appox.initializeAgency(ProtoFilePath)

  // 初始化 Bridge 消息队列
  window.top.onmessage = (event) => {
    biBridge.onWindowMessage(event.data)
  }

  // 定时更新数据
  setInterval(() => {
    controllerStore.updateAll()
    toolPanelStore.updateToolPanelButtons()
    standaloneTaskStore.updateRunButton()
    consoleProcedureStore.updateRunButton()
    contentTransferPanelStore.updateContentTransferState()
    htmlModuleStore.updateAppStatus()
    busChannelsStore.updateChannelStatuses()
    videoChannelsStore.updateChannelStatuses()
    otherChannelsStore.updateOtherChannels()
    systemStatusStore.updateSystemStatus()
    videoMonitorStore.updateChannelList()
    videoMonitorStore.updateVideoImages()
    signalMonitorStore.updateSignalInfo()
    birdViewStore.updateCanvas()
    busTracerStore.updateModel()
    pointCloudMonitorStore.updateCanvas()
  }, 15)

  // 显示HTML模块内容
  htmlModuleStore.loadDevelPanel()
}

// 挂载应用
app.mount('#app')

// 初始化应用
initializeApp()